/**
 * 发邮件 工具类
 */
const { emailName, emailPassword } = require("./resource/mailConfig"); //配置文件
const nodemailer = require('nodemailer');//发邮件
const moment = require("moment"); //日期
const fs = require('fs-extra');
// const { ascii2native } = require('./utils'); //工具类

const transporter = nodemailer.createTransport({
	//https://nodemailer.com/smtp/well-known/ 支持列表
	//https://github.com/nodemailer/nodemailer-wellknown/blob/master/services.json 配置
	// host: "smtp.exmail.qq.com", // 主机
	service: 'qq',
	port: 465, // SMTP 端口
	secureConnection: true, // 使用 SSL
	auth: {
		user: emailName,
		pass: emailPassword
	}
});


/**
 * 发邮件 普通 html
 * @param {Object} title 标题
 * @param {Object} text 内容
 */
async function sendMailForHtml(title, text) {
	// 当天日期
	let now = moment();
	let today = now.clone().add(0, 'days').format('YYYY-MM-DD');
	let toListFile = await fs.readJSON('./resource/mail.json')
	let toListInit = toListFile.toList.join(',') // array转str	
	let mailOptions = {
		from: emailName, // 发件地址
		to: toListInit, // 收件列表
		subject: `${title}(${today})`, // 标题	
		html: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'+ text // html 内容
	};

	transporter.sendMail(mailOptions, function(error, info) {
		if(error) {
			return console.log('邮件发送出错', error);
		}
		console.log('Message sent: ' + info.response);
	});
}


module.exports = {
	mailSend: sendMailForHtml
};